package com.ebt.m.fileExplore.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.fileExplore.adapter.AdapterFileExplore;
import com.ebt.m.fileExplore.interfaces.IBackHandlerActivity;
import com.ebt.m.fileExplore.interfaces.IBackHandlerFragment;
import com.ebt.m.fileExplore.model.ItemFile;
import com.ebt.m.fileExplore.util.CompareHelper;
import com.ebt.m.widget.MDEBTDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

public class FragmentFileExplore extends Fragment implements OnItemClickListener, View.OnClickListener, IBackHandlerFragment {

    public static final String FILE_EXPLORE_MODE = "mode";
    public static final String FILE_EXPLORE_MODE_NORMAL = "normal";

    public static final String FILE_EXPLORE_ROOT_DIR = "root_dir";

    private final static int FROM_VIEW = 0;
    private final static int FROM_KEY = 1;

    private View contentView;
    private TextView back;
    private TextView title;
    private ListView list;
    private Bundle mGetBundle;
    private String mFileExploreMode;
    private String mFileRootDir;
    private File mExternalDir;
    private String mSdcardPath;
    private AdapterFileExplore adapterFileExplore;
    private String currentDir;
    private ArrayList<ItemFile> items = new ArrayList<ItemFile>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMode();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        contentView = initViews(inflater);
        return contentView;
    }

    private Context mContext;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        this.getActivity().getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                showFiles();
            }
        });

        mContext = this.getActivity();
        if (mContext instanceof IBackHandlerActivity) {
            ((IBackHandlerActivity) mContext).setSelectedFragment(this);
        }
    }

    public static FragmentFileExplore newInstance(String mode, String rootDir, FileExploreListener fileExploreListener) {
        Bundle bundle = new Bundle();
        bundle.putString(FILE_EXPLORE_MODE, mode);
        bundle.putString(FILE_EXPLORE_ROOT_DIR, rootDir);
        FragmentFileExplore fragmentFileExplore = new FragmentFileExplore();
        fragmentFileExplore.setArguments(bundle);
        fragmentFileExplore.setFileExploreListener(fileExploreListener);
        return fragmentFileExplore;
    }

    /**
     * init root files
     */
    private void showFiles() {

        mExternalDir = Environment.getExternalStorageDirectory();
        if (mExternalDir == null) {
            Toast.makeText(getActivity(), R.string.file_explore_cannot_find_sdcard, Toast.LENGTH_LONG).show();
            return;
        }

        mSdcardPath = mExternalDir.getAbsolutePath();
        if (mFileRootDir != null && checkIfExists(mFileRootDir)) {
            showFileDir(mFileRootDir, true, true);
        } else {
            showFileDir(mSdcardPath, true, true);
        }
    }

    private boolean checkIfExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    private void setCurrentDir(String currentDir) {
        this.currentDir = currentDir;
    }

    private void updateTitle(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        String filePath1 = filePath;

        if (filePath1.toLowerCase().contains("sdcard")) {
            filePath1 = filePath1.replace("sdcard", "SD卡");
        } else if (filePath1.equals("/")) {
            filePath1 = "根目录";
        }

        if (filePath1.toLowerCase().startsWith("/storage")) {
            filePath1 = filePath1.replace("/storage", "存储盘");
        }

        title.setText(getString(R.string.file_explore_currentdir, filePath1));
    }

    private void showFileDir(String path, boolean init, boolean forword) {
        setCurrentDir(path);
        updateTitle(path);
        items.clear();

        File[] files = new File(path).listFiles();

        for (File f : files) {
            items.add(convertFileToItemFile(f));
        }

        Collections.sort(items, CompareHelper.COMPARATOR_FILE_ITEM);

        if (init) {
            adapterFileExplore = new AdapterFileExplore(this.getActivity(), items);
            list.setAdapter(adapterFileExplore);
        } else {
            adapterFileExplore.notifyDataSetChanged();
        }
        if (forword) {
            if (adapterFileExplore.getCount() > 0) {
                list.setSelection(0);
            }
        }
    }

    private ItemFile convertFileToItemFile(File file) {
        if (file.isDirectory()) {
            return new ItemFile(ItemFile.TYPE_FOLDER, file.getName(), file.getPath());
        } else {
            return new ItemFile(ItemFile.TYPE_FILE, file.getName(), file.getPath());
        }
    }

    private View initViews(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_file_explore, null);
        title = (TextView) view.findViewById(R.id.title);
        back = (TextView) view.findViewById(R.id.back);
        back.setOnClickListener(this);
        list = (ListView) view.findViewById(R.id.list);

        list.setOnItemClickListener(this);
        return view;
    }

    private void initMode() {
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            mFileExploreMode = mGetBundle.getString(FILE_EXPLORE_MODE);
            mFileRootDir = mGetBundle.getString(FILE_EXPLORE_ROOT_DIR);
        }
    }

    private String getParentFileDir(String currentPath) {
        File file = new File(currentPath);
        return file.getParent();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ItemFile item = items.get(position);
        File file = new File(item.path);

        if (file.exists() && file.canRead()) {
            if (item.isDirectory()) {
                showFileDir(item.path, false, true);
            } else {
                handleFile(file);
            }
        } else {
            popAlert(this.getActivity(), R.string.no_permission);
        }
    }

    private void popAlert(Context context, int stringId) {
        popAlert(context, context.getString(stringId));
    }

    private void popAlert(Context context, String message) {

        String[] messages = new String[]{"没有权限读取此文件"};
        new MDEBTDialog.Builder(getActivity())
                .setMessages(messages)
                .setTitle("提示")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setShowNegativeButton(false)
                .setShowPositiveButton(true)
                .setShowTitle(true)
                .create()
                .show();
    }

    private void handleFile(File file) {
        String[] messages = new String[]{"选择此文件？"};
        new MDEBTDialog.Builder(getActivity())
                .setMessages(messages)
                .setTitle("文件选择")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (fileExploreListener != null) {
                            fileExploreListener.result(file);
                        }
                    }
                })
                .setContentViewClickable(false)
                .create()
                .show();
    }

    public interface FileExploreListener {
        void result(File file);
    }

    private FileExploreListener fileExploreListener;

    private void setFileExploreListener(FileExploreListener fileExploreListener) {
        this.fileExploreListener = fileExploreListener;
    }


    private void displayToast(String message) {
        Toast.makeText(this.getActivity(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                back(FROM_VIEW);
                break;
        }
    }

    @Override
    public Object[] onBackPressed() {
        boolean b = back(FROM_KEY);
        Object[] o = new Object[1];
        o[0] = Boolean.valueOf(b);
        return o;
    }

    private boolean back(int source) {
        if (!"/".equals(currentDir)) {
            currentDir = getParentFileDir(currentDir);
            if (!TextUtils.isEmpty(currentDir)) {
                File f = new File(currentDir);
                if (!f.exists() || f.listFiles() == null) {
                    getActivity().finish();
                    return false;
                }

                showFileDir(currentDir, false, false);
            }
            return true;
        }
        if (source == FROM_VIEW) {
            getActivity().finish();
        }
        return false;
    }

}
